package com.ruoyi.common.utils.http;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DmsHttpUtils {

    private static final Logger log = LoggerFactory.getLogger(DmsHttpUtils.class);
    /**
     * 1、封装各种请求
     * 2、param参数定制、header参数定制、body参数定制。
     */
    public static Map<String, Object> sendHttpGet(String url){
        return DmsHttpUtils.sendHttpGet(url,null);
    }

    public static Map<String, Object> sendHttpGet(String url, Map<String,String> header)
    {
        // 初始化返回结果
        Map<String, Object> newRes = new HashMap<>();
        // 初始化请求返回结果
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try
        {
            long startTime=System.currentTimeMillis();   //获取开始时间
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            if(header != null){
                for (Map.Entry<String, String> entry:
                        header.entrySet()) {
                    connection.setRequestProperty(entry.getKey(),entry.getValue());
                }
            }
            connection.connect();
            long endTime=System.currentTimeMillis(); //获取结束时间
            if(httpURLConnection.getResponseCode() == 200){
                InputStream inputStream = connection.getInputStream();
                in = new BufferedReader(new InputStreamReader(inputStream, Constants.UTF8));
//            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
                String line;
                while ((line = in.readLine()) != null)
                {
                    result.append(line);
                }
//            System.out.println(connection.getHeaderFields());
                log.info("recv - {}", result);
                newRes.put("status",httpURLConnection.getResponseCode());
                newRes.put("ResponseTime",endTime-startTime);
                newRes.put("ResponseData",result);
            }else{
                newRes.put("errorMsg",httpURLConnection.getResponseCode());
            }

        }
        catch (ConnectException e)
        {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url , e);
            newRes.put("errorMsg",e.getMessage());
        }
        catch (SocketTimeoutException e)
        {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url, e);
            newRes.put("errorMsg",e.getMessage());
        }
        catch (IOException e)
        {
            log.error("调用HttpUtils.sendGet IOException, url=" + url, e);
            newRes.put("errorMsg",e.getMessage());
        }
        catch (Exception e)
        {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url, e);
            newRes.put("errorMsg",e.getMessage());
        }
        finally
        {
            try
            {
                if (in != null)
                {
                    in.close();
                }
            }
            catch (Exception ex)
            {
                log.error("调用in.close Exception, url=" + url, ex);
                newRes.put("errorMsg",ex.getMessage());
            }
        }
        return newRes;
    }

    public static Map<String, Object> sendHttpPost(String url, String bodyType, String param)
    {
        return DmsHttpUtils.sendHttpPost(url,bodyType,null,param);
    }

    public static Map<String, Object> sendHttpPost(String url, String bodyType, Map<String,String> header)
    {
        return DmsHttpUtils.sendHttpPost(url,bodyType,header,null);
    }

    public static Map<String, Object> sendHttpPost(String url)
    {
        return DmsHttpUtils.sendHttpPost(url,"none",null,null);
    }

    public static Map<String, Object> sendHttpPost(String url, String bodyType, Map<String,String> header, String param)
    {
        Map<String, Object> newRes = new HashMap<>();
        PrintWriter out = null;
//        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            String urlNameString = url;
            log.info("sendPost - {}", urlNameString);
            long startTime=System.currentTimeMillis();   //获取开始时间
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
//            conn.setRequestProperty("Charset", "UTF-8");
            if("formData".equals(bodyType)){
                conn.setRequestProperty("Content-type", "utf-8");
            }else {
                conn.addRequestProperty("Content-type", "application/json");
            }
//            conn.setRequestProperty("contentType", "utf-8");
            if(header != null){
                for (Map.Entry<String, String> entry:
                        header.entrySet()) {
                    conn.setRequestProperty(entry.getKey(),entry.getValue());
                }
            }
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
//            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            if (param != null){
//                param = java.net.URLEncoder.encode(param, "UTF-8");
                out.write(param);
            }
            out.flush();
            InputStream inputStream = conn.getInputStream();
            in = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            long endTime=System.currentTimeMillis(); //获取结束时间
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
            newRes.put("status",httpURLConnection.getResponseCode());
            newRes.put("ResponseTime",endTime-startTime);
            newRes.put("ResponseData",result);
        }
        catch (ConnectException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                newRes.put("errorMsg",ex.getMessage());
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return newRes;
    }

    public static Map<String, Object> sendHttpPut(String url, String param){
        return DmsHttpUtils.sendHttpPut(url,null,param);
    }


    public static Map<String, Object> sendHttpPut(String url, Map<String,String> header, String param)
    {
        Map<String, Object> newRes = new HashMap<>();
        PrintWriter out = null;
//        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            String urlNameString = url;
            log.info("sendPost - {}", urlNameString);
            long startTime=System.currentTimeMillis();   //获取开始时间
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
//            conn.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.addRequestProperty("Content-type", "application/json");
//            conn.setRequestProperty("contentType", "utf-8");
            if(header != null){
                for (Map.Entry<String, String> entry:
                        header.entrySet()) {
                    conn.setRequestProperty(entry.getKey(),entry.getValue());
                }
            }
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("PUT");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setInstanceFollowRedirects(true);
            out = new PrintWriter(httpURLConnection.getOutputStream());
//            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            if (param != null){
//                param = java.net.URLEncoder.encode(param, "UTF-8");
                out.write(param);
            }
            out.flush();
            InputStream inputStream = httpURLConnection.getInputStream();
            in = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            long endTime=System.currentTimeMillis(); //获取结束时间
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
            newRes.put("status",httpURLConnection.getResponseCode());
            newRes.put("ResponseTime",endTime-startTime);
            newRes.put("ResponseData",result);
        }
        catch (ConnectException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                newRes.put("errorMsg",ex.getMessage());
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return newRes;
    }

    public static Map<String, Object> sendHttpPatch(String url, String param){
        return DmsHttpUtils.sendHttpPatch(url,null,param);
    }


    public static Map<String, Object> sendHttpPatch(String url, Map<String,String> header, String param)
    {
        Map<String, Object> newRes = new HashMap<>();
        PrintWriter out = null;
//        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            String urlNameString = url;
            log.info("sendPost - {}", urlNameString);
            long startTime=System.currentTimeMillis();   //获取开始时间
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.addRequestProperty("Content-type", "application/json");
            httpURLConnection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setRequestMethod("POST");
            if(header != null){
                for (Map.Entry<String, String> entry:
                        header.entrySet()) {
                    conn.setRequestProperty(entry.getKey(),entry.getValue());
                }
            }
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("PUT");
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setInstanceFollowRedirects(true);
            out = new PrintWriter(httpURLConnection.getOutputStream());
//            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            if (param != null){
//                param = java.net.URLEncoder.encode(param, "UTF-8");
                out.write(param);
            }
            out.flush();
            InputStream inputStream = httpURLConnection.getInputStream();
            in = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            long endTime=System.currentTimeMillis(); //获取结束时间
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
            newRes.put("status",httpURLConnection.getResponseCode());
            newRes.put("ResponseTime",endTime-startTime);
            newRes.put("ResponseData",result);
        }
        catch (ConnectException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                newRes.put("errorMsg",ex.getMessage());
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return newRes;
    }


    public static Map<String, Object> sendHttpDel(String url, String param){
        return DmsHttpUtils.sendHttpDel(url,null,param);
    }


    public static Map<String, Object> sendHttpDel(String url, Map<String,String> header, String param)
    {
        Map<String, Object> newRes = new HashMap<>();
        PrintWriter out = null;
//        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try
        {
            String urlNameString = url;
            log.info("sendPost - {}", urlNameString);
            long startTime=System.currentTimeMillis();   //获取开始时间
            URL realUrl = new URL(urlNameString);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            httpURLConnection.setRequestMethod("DELETE");
//            conn.setRequestProperty("Charset", "UTF-8");
//            httpURLConnection.addRequestProperty("Content-type", "application/json");
//            conn.setRequestProperty("contentType", "utf-8");
            if(header != null){
                for (Map.Entry<String, String> entry:
                        header.entrySet()) {
                    conn.setRequestProperty(entry.getKey(),entry.getValue());
                }
            }
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            out = new PrintWriter(httpURLConnection.getOutputStream());
//            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            if (param != null){
//                param = java.net.URLEncoder.encode(param, "UTF-8");
                out.write(param);
            }
            out.flush();
            InputStream inputStream = httpURLConnection.getInputStream();
            in = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            long endTime=System.currentTimeMillis(); //获取结束时间
            String line;
            while ((line = in.readLine()) != null)
            {
                result.append(line);
            }
            log.info("recv - {}", result);
            newRes.put("status",httpURLConnection.getResponseCode());
            newRes.put("ResponseTime",endTime-startTime);
            newRes.put("ResponseData",result);
        }
        catch (ConnectException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        }
        catch (SocketTimeoutException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        }
        catch (IOException e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        }
        catch (Exception e)
        {
            newRes.put("errorMsg",e.getMessage());
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        }
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            }
            catch (IOException ex)
            {
                newRes.put("errorMsg",ex.getMessage());
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return newRes;
    }
//    public static void main(String[] args) {
//        Map<String,Object> res = new HashMap<>();
//        String url = "http://172.16.11.21:18092/api/verify/file";
//        String param = "containerName=dmsUK&passWd=123456789";
//        res = DmsHttpUtils.sendHttpPost(url);
//        System.out.println(res);
//    }
}
